package com.quwan.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片工具类
 *
 * @author lt
 * @Date 2021/12/1 12:30 下午
 */
public class ImageUtils {

    private static Logger logger = LoggerFactory.getLogger(ImageUtils.class);

    public static void main(String[] args) throws IOException {
        long l = System.currentTimeMillis();
        compressPicForScale(new FileInputStream(new File("D:\\temp\\img\\example.jpg")), 1024, 1024,"publicservice");
        System.out.println(System.currentTimeMillis() - l);
    }

    /**
     * 图片压缩
     * @param inputStream 输入流
     * @param srcSize 需要压缩到的大小
     * @param desFileSize 当前文件大小
     * @param appName 实例名称
     * @return
     */
    public static File compressPicForScale(InputStream inputStream, int srcSize, long desFileSize,String appName) {
//        File result = new File("D:/test.jpg");
        String name = UUIDUtils.getSerialNumber();
        File result = new File("D:\\temp\\img\\example1111.jpg");
        double accuracy = getAccuracy(srcSize / 1024);
        boolean flag = true;
        try {
            while (flag) {
                Thumbnails.of(inputStream)
                        .scale(accuracy)
                        .toFile(result);
                if (result.length() < desFileSize * 1024) {
                    flag = false;
                } else {
                    inputStream = new FileInputStream(result);
                }
            }
        } catch (Exception e) {
            logger.error("【图片压缩】msg=图片压缩失败!", e);
        }
        return result;
    }

    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 4096) {
            accuracy = 0.85;
        } else if (size < 8192) {
            accuracy = 0.6;
        } else if (size < 12288) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }

}
